RestTemplate হলো স্প্রিং বুটের একটি ক্লাস যা RESTful API কল করতে ব্যবহৃত হয়। এটি সিঙ্ক্রোনাস এবং ব্লকিং ভিত্তিক API কল করতে ব্যবহৃত হয়। একটি ভালোভাবে কনফিগার করা RestTemplate ক্লাস এপ্লিকেশনের কার্যক্ষমতা উন্নত করতে পারে।
নিচে RestTemplate এর কনফিগারেশন করার ধাপগুলো দেখানো হলো:
১. RestTemplate Bean ডিফাইন করুন
আপনার অ্যাপ্লিকেশনে RestTemplate ব্যবহারের জন্য একটি Bean ডিফাইন করতে হবে। এটি @Configuration ক্লাসে যুক্ত করা হয়।
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
২. Custom RequestFactory যুক্ত করুন (Timeout সেট করা)
RestTemplate-এর মাধ্যমে টাইমআউট সেট করার জন্য একটি কাস্টম RequestFactory ব্যবহার করা যেতে পারে।
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
// টাইমআউট কনফিগারেশন
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // কানেকশন টাইমআউট (মিলিসেকেন্ডে)
.setSocketTimeout(5000) // রেসপন্স টাইমআউট (মিলিসেকেন্ডে)
.build();
// HTTP Client কনফিগারেশন
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
// RestTemplate এর জন্য RequestFactory তৈরি
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}
৩. Connection Pooling যুক্ত করা
যদি অনেক বেশি রিকোয়েস্ট হ্যান্ডল করতে হয়, তবে Connection Pooling এর মাধ্যমে কার্যক্ষমতা উন্নত করা যায়।
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.config.RequestConfig;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
// Connection Pooling কনফিগারেশন
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(50); // সর্বোচ্চ কানেকশন
connectionManager.setDefaultMaxPerRoute(20); // প্রতি রুটের জন্য সর্বোচ্চ কানেকশন
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}
৪. Interceptors (Logging বা Custom Headers যুক্ত করা)
RestTemplate এর সাথে ClientHttpRequestInterceptor ব্যবহার করে লগিং বা হেডার যুক্ত করা যায়।
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
// Interceptor যুক্ত করা
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add((request, body, execution) -> {
// Custom Headers
request.getHeaders().add("Authorization", "Bearer your-token");
return execution.execute(request, body);
});
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
৫. Exception Handling যুক্ত করা
কাস্টম ResponseErrorHandler ব্যবহার করে Exception Handling সেটআপ করতে পারেন।
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new CustomResponseErrorHandler());
return restTemplate;
}
private static class CustomResponseErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().isError();
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// Custom Error Handling Logic
System.out.println("Error: " + response.getStatusCode());
}
}
}
RestTemplate কনফিগারেশনের সুবিধা:
- Timeout সেট করা: সার্ভার স্লো হলে অ্যাপ্লিকেশন ব্লকিং এড়ানো যায়।
- Connection Pooling: কার্যক্ষমতা বৃদ্ধি এবং কম সময়ে অনেক বেশি রিকোয়েস্ট পরিচালনা করা।
- Interceptor ব্যবহার: লগিং এবং অথেনটিকেশন হ্যান্ডলিং সহজ হয়।
- Custom Error Handling: সহজে এপ্লিকেশন ত্রুটি শনাক্ত এবং হ্যান্ডল করা যায়।
এই কনফিগারেশনগুলো আপনার প্রজেক্টের REST API কলিং ব্যবস্থাকে আরও দক্ষ এবং স্থিতিশীল করে তুলবে।
Spring Boot-এ RestTemplate কনফিগার করা এবং একটি Bean তৈরি করা একটি সাধারণ প্রক্রিয়া। এটি ব্যবহার করে আপনি সহজেই HTTP অনুরোধগুলি পরিচালনা করতে পারেন।
RestTemplate কি?
RestTemplate হলো Spring-এর একটি ক্লাস, যা HTTP ক্লায়েন্ট হিসেবে কাজ করে এবং RESTful সেবা বা API এর সাথে যোগাযোগ করার জন্য ব্যবহৃত হয়। এটি সিনক্রোনাস HTTP অনুরোধ পাঠানোর জন্য ব্যবহৃত হয়।
RestTemplate Bean তৈরি করার ধাপসমূহ:
1. RestTemplate Bean ডিফাইন করা:
আপনার অ্যাপ্লিকেশনে RestTemplate Bean ডিফাইন করতে হবে, যাতে এটি স্প্রিং কন্টেইনার দ্বারা পরিচালিত হয় এবং অন্য যেকোনো স্থানে ইনজেক্ট করা যায়।
উদাহরণ:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2. Custom Configuration (Optional):
আপনি চাইলে RestTemplate-এর জন্য কিছু কাস্টম কনফিগারেশন যেমন টাইমআউট বা ইন্টারসেপ্টর সেট করতে পারেন।
উদাহরণ (Custom Timeout এবং Interceptor):
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
// Optional: Add Interceptors if needed
// restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
return restTemplate;
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 5 seconds connection timeout
factory.setReadTimeout(5000); // 5 seconds read timeout
return factory;
}
}
3. RestTemplate ব্যবহার করা:
@Autowired অথবা @Bean এর মাধ্যমে RestTemplate ইনজেক্ট করা হয় এবং তারপর এটি ব্যবহার করা হয়।
উদাহরণ:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
@Autowired
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String fetchDataFromServer() {
String url = "https://api.example.com/data";
return restTemplate.getForObject(url, String.class);
}
}
কনফিগারেশন ডিটেইলস:
- Connection Timeout: সার্ভারে সংযোগ স্থাপনে সময় লাগলে সেটি কতক্ষণ পর্যন্ত অপেক্ষা করবে।
- Read Timeout: ডেটা পড়ার সময় অপেক্ষার সময় নির্ধারণ করে।
- Interceptors: HTTP অনুরোধ ও প্রতিক্রিয়ার আগে এবং পরে কাস্টম প্রসেসিং করতে পারে।
Application.properties ফাইলে অতিরিক্ত কনফিগারেশন:
আপনি চাইলে প্রপার্টি ফাইলে টাইমআউট এবং অন্যান্য কনফিগারেশন সেট করতে পারেন।
resttemplate.connection.timeout=5000
resttemplate.read.timeout=5000
কেন RestTemplate Bean তৈরি করবেন?
- Reusability: Bean তৈরি করলে এটি বিভিন্ন স্থানে পুনরায় ব্যবহার করা যায়।
- Maintainability: কনফিগারেশনগুলো একটি কেন্দ্রীয় স্থানে থাকে।
- Customization: কাস্টম কনফিগারেশন সহজে অ্যাড করা যায়।
এভাবে আপনি RestTemplate Bean তৈরি করে HTTP অনুরোধগুলি সহজেই পরিচালনা করতে পারবেন।
Spring Boot ক্লায়েন্টে (Spring Boot Client) Custom HTTP Headers যোগ করা সাধারণত API-এর নির্দিষ্ট চাহিদা অনুযায়ী করা হয়। Spring Boot-এ এই কাজটি করা যায় RestTemplate, WebClient, বা Feign Client ব্যবহার করে।
নিচে বিভিন্ন পদ্ধতিতে Custom HTTP Headers যোগ করার প্রক্রিয়া দেখানো হলো:
১. RestTemplate ব্যবহার করে Custom HTTP Headers যোগ করা
উদাহরণ:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getDataWithHeaders() {
String url = "https://jsonplaceholder.typicode.com/posts";
// Custom Headers সেট করা
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your-token");
headers.set("Custom-Header", "HeaderValue");
// HttpEntity তৈরি করা
HttpEntity<String> entity = new HttpEntity<>(headers);
// API কল করা
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, entity);
return response.getBody();
}
}
RestTemplate Bean কনফিগারেশন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
২. WebClient ব্যবহার করে Custom HTTP Headers যোগ করা
উদাহরণ:
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class ApiService {
private final WebClient webClient;
public ApiService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://jsonplaceholder.typicode.com").build();
}
public String getDataWithHeaders() {
return webClient.get()
.uri("/posts")
.header("Authorization", "Bearer your-token")
.header("Custom-Header", "HeaderValue")
.retrieve()
.bodyToMono(String.class)
.block();
}
}
WebClient Bean কনফিগারেশন (ঐচ্ছিক):
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfig {
@Bean
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
৩. Feign Client ব্যবহার করে Custom HTTP Headers যোগ করা
Feign Client Interface:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(name = "apiClient", url = "https://jsonplaceholder.typicode.com")
public interface ApiClient {
@GetMapping("/posts")
String getPostsWithHeaders(
@RequestHeader("Authorization") String token,
@RequestHeader("Custom-Header") String customHeader
);
}
Feign Client ব্যবহার:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ApiService {
@Autowired
private ApiClient apiClient;
public String getDataWithHeaders() {
return apiClient.getPostsWithHeaders("Bearer your-token", "HeaderValue");
}
}
Feign Configuration (Optional):
feign.client.config.default.loggerLevel=full
feign.client.config.default.connectTimeout=5000
feign.client.config.default.readTimeout=5000
৪. কাস্টম HTTP হেডারের ব্যবহার কোথায় প্রয়োজন হতে পারে?
- Authentication বা Authorization:
Authorization: Bearer <token>বাAPI-Key: <key>।
- Custom Metadata:
- ক্লায়েন্টের কিছু অতিরিক্ত তথ্য API-তে পাঠাতে।
- Tracking এবং Debugging:
Request-ID,Correlation-IDহেডার ব্যবহার করা হয়।
- Content Negotiation:
Accept,Content-Typeহেডার পরিবর্তন করতে।
উপসংহার
Spring Boot-এ Custom HTTP Headers যোগ করার উপায় নির্ভর করে আপনি কোন HTTP ক্লায়েন্ট ব্যবহার করছেন। RestTemplate, WebClient, এবং Feign Client—সবগুলোতেই এটি খুব সহজে করা যায়।
যদি আপনার কোনো নির্দিষ্ট প্রয়োজনে সাহায্য দরকার হয়, জানাবেন। 😊
স্প্রিং বুটে RestTemplate কনফিগার করার সময় টাইমআউট এবং এক্সসেপশন হ্যান্ডলিং যুক্ত করার জন্য কাস্টম কনফিগারেশন প্রয়োজন। নিচে এই কনফিগারেশন এবং হ্যান্ডলিংয়ের উদাহরণ তুলে ধরা হলো:
RestTemplate-এর জন্য টাইমআউট কনফিগার করার সময় HttpComponentsClientHttpRequestFactory ব্যবহার করা হয়। এটি কানেকশন টাইমআউট এবং রিড টাইমআউট সেট করার জন্য ব্যবহৃত হয়।
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
// Set connection timeout (milliseconds)
factory.setConnectTimeout(5000);
// Set read timeout (milliseconds)
factory.setReadTimeout(5000);
return new RestTemplate(factory);
}
}
টাইমআউটের জন্য পুলিং সংযোগ ব্যবহারের উদাহরণ
পুলিং কানেকশন ব্যবহারের মাধ্যমে টাইমআউট এবং কার্যকারিতা উন্নত করা যায়:
@Bean
public RestTemplate restTemplateWithPooling() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100); // সর্বোচ্চ ১০০ কানেকশন
connectionManager.setDefaultMaxPerRoute(20); // প্রতি রাউটে সর্বোচ্চ ২০ কানেকশন
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
factory.setConnectTimeout(5000); // কানেকশন টাইমআউট
factory.setReadTimeout(5000); // রিড টাইমআউট
return new RestTemplate(factory);
}
Exception Handling
REST API কল করার সময় ত্রুটি হ্যান্ডল করার জন্য RestTemplate-এ কাস্টম ResponseErrorHandler ব্যবহার করা যায়। এটি ত্রুটিপূর্ণ HTTP রেসপন্স হ্যান্ডল করতে ব্যবহৃত হয়।
উদাহরণ:
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// Custom error handling logic
if (response.getStatusCode().is4xxClientError()) {
throw new RestClientException("Client Error: " + response.getStatusCode());
} else if (response.getStatusCode().is5xxServerError()) {
throw new RestClientException("Server Error: " + response.getStatusCode());
} else {
super.handleError(response);
}
}
}
এই কাস্টম হ্যান্ডলার RestTemplate-এ যুক্ত করুন:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new CustomResponseErrorHandler());
return restTemplate;
}
Exception Handling Controller Advice
আপনার অ্যাপ্লিকেশনের সব REST কলের জন্য @ControllerAdvice ব্যবহার করে গ্লোবাল এক্সসেপশন হ্যান্ডল করতে পারেন:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RestClientException.class)
public ResponseEntity<String> handleRestClientException(RestClientException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error: " + ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + ex.getMessage());
}
}
পূর্ণ উদাহরণ
কাস্টম টাইমআউট এবং এক্সসেপশন হ্যান্ডলিংসহ RestTemplate কনফিগার:
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000); // কানেকশন টাইমআউট
factory.setReadTimeout(5000); // রিড টাইমআউট
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(new CustomResponseErrorHandler());
return restTemplate;
}
}
এইভাবে আপনি RestTemplate-এর জন্য টাইমআউট এবং এক্সসেপশন হ্যান্ডলিং কনফিগার করতে পারবেন। এটি আপনার ক্লায়েন্ট অ্যাপ্লিকেশনকে আরও স্থিতিশীল এবং রিলায়েবল করবে।
RestTemplate হলো Spring Framework-এর একটি ক্লাস, যা HTTP API-এর মাধ্যমে সার্ভারের সাথে ডেটা আদান-প্রদান করার জন্য ব্যবহৃত হয়। এটি GET, POST, PUT, DELETE ইত্যাদি HTTP মেথড সাপোর্ট করে।
RestTemplate কনফিগারেশন উদাহরণ
১. RestTemplate Bean কনফিগার করা
আপনার স্প্রিং বুট অ্যাপ্লিকেশনে একটি @Configuration ক্লাস তৈরি করুন এবং সেখানে RestTemplate এর জন্য একটি @Bean ডিফাইন করুন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
২. RestTemplate ব্যবহার করে HTTP কল করা
আপনার কন্ট্রোলার বা সার্ভিস ক্লাসে RestTemplate ব্যবহার করতে পারেন:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ApiController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consume-api")
public String consumeApi() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
return restTemplate.getForObject(url, String.class);
}
}
উদাহরণ: RestTemplate দিয়ে GET, POST, PUT, DELETE অপারেশন
১. GET রিকুয়েস্ট
@GetMapping("/get-example")
public String getExample() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
return restTemplate.getForObject(url, String.class);
}
২. POST রিকুয়েস্ট
@PostMapping("/post-example")
public String postExample() {
String url = "https://jsonplaceholder.typicode.com/posts";
Post post = new Post(1, "My Title", "This is a sample body.");
return restTemplate.postForObject(url, post, String.class);
}
class Post {
private int userId;
private String title;
private String body;
// Constructor, getters, and setters
public Post(int userId, String title, String body) {
this.userId = userId;
this.title = title;
this.body = body;
}
}
৩. PUT রিকুয়েস্ট
@PutMapping("/put-example")
public void putExample() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
Post updatedPost = new Post(1, "Updated Title", "This is an updated body.");
restTemplate.put(url, updatedPost);
}
৪. DELETE রিকুয়েস্ট
@DeleteMapping("/delete-example")
public void deleteExample() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
restTemplate.delete(url);
}
RestTemplate-এর অ্যাডভান্সড কনফিগারেশন
১. টাইমআউট এবং কাস্টম কনফিগারেশন
কাস্টম HTTP ক্লায়েন্ট দিয়ে RestTemplate কনফিগার করতে পারেন:
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.HttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 5 seconds
.setSocketTimeout(5000) // 5 seconds
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}
}
৩. RestTemplate তে হেডার যোগ করা
আপনার HTTP রিকুয়েস্টে হেডার যোগ করতে চাইলে HttpHeaders এবং HttpEntity ব্যবহার করুন:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
@GetMapping("/header-example")
public String headerExample() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer your-token");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return response.getBody();
}
উপসংহার
উপরে দেওয়া কনফিগারেশন এবং উদাহরণগুলোর মাধ্যমে আপনি RestTemplate ব্যবহার করে যেকোনো HTTP API কল সহজে পরিচালনা করতে পারবেন। এটি মাইক্রোসার্ভিস বা এক্সটার্নাল API-এর সাথে ইন্টিগ্রেশন করতে বেশ কার্যকর।
Read more